package com.wing.web.db.config.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.wing.common.constant.GlobalConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

/**
 * spring动态数据源（需要继承AbstractRoutingDataSource）
 *
 * @author owen
 * @create 2017年7月2日
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Value("${database.prefix}")
    private String prefix;
    @Value("${database.ip}")
    private String address;
    @Value("${database.port}")
    private String port;
    @Value("${spring.datasource.druid.username}")
    private String username;
    @Value("${spring.datasource.druid.password}")
    private String password;

    // 当前使用的数据源标识
    public static ThreadLocal<String> name = new ThreadLocal<>();

    // 当前所有数据源
    public static Map<Object, Object> targetDataSources = new HashMap<>();

    // 业务数据库前缀
    public static final String BUSINESS_PREFIX = "szgc";

    // 用户数据库前缀
    public static final String USER_PREFIX = "szgc-user";

    @Autowired
    DataSource dataSourceCore;

    // 返回当前数据源标识
    @Override
    public Object determineCurrentLookupKey() {
        String dsKey= name.get();
        logger.info("---------------------------determineCurrentLookupKey datasource key:"+dsKey+",thread name:"+Thread.currentThread().getName()+","+Thread.currentThread().getId());
        if (StringUtils.isBlank(dsKey)){
            dsKey="core";
        }
        logger.info("dsKey:"+dsKey);
        return dsKey;
    }

    @Override
    public void afterPropertiesSet() {
        targetDataSources.put("core", dataSourceCore);
        logger.info("query datasource start");
        // 查询数据源配置
        queryDataSourceConfig();
        logger.info("query datasource end");


        super.setTargetDataSources(targetDataSources);

        // 为defaultTargetDataSource 设置默认的数据源
        super.setDefaultTargetDataSource(dataSourceCore);

        super.afterPropertiesSet();
    }

    private void queryDataSourceConfig() {
//        String url = "jdbc:mysql://"+GlobalConstants.ADDRESS+":"+GlobalConstants.PORT+"/"+GlobalConstants.USER_PREFIX+"?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai";
//        String username = GlobalConstants.USERNAME;
//        String password = GlobalConstants.PASSWORD;
        String url = "jdbc:mysql://"+address+":"+port+"/"+prefix+"-user"+"?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai";
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        Connection newConn = null; // 连接刚刚创建的数据库
        try {
            newConn = DriverManager.getConnection(url, username, password);
            Statement newSmt = newConn.createStatement();
            String sql = "select * from `sys_data_source`";
            ResultSet resultSet = newSmt.executeQuery(sql);
            while (resultSet.next()){
                String name = resultSet.getString("name");
                String nameStr = "";
                if(StringUtils.isNotBlank(name)){
                    nameStr = "-"+name;
                }
                String ip = resultSet.getString("ip");
                String port = resultSet.getString("port");
                DataSource dataSource1 = DruidDataSourceBuilder.create().build();
//                ((DruidDataSource) dataSource1).setUrl("jdbc:mysql://"+ip+":"+port+"/"+GlobalConstants.BUSINESS_PREFIX+nameStr+"?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai");
                ((DruidDataSource) dataSource1).setUrl("jdbc:mysql://"+ip+":"+port+"/"+prefix+nameStr+"?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai");
                ((DruidDataSource) dataSource1).setUsername(username);
                ((DruidDataSource) dataSource1).setPassword(password);
                ((DruidDataSource) dataSource1).setDriverClassName(driverClassName);
                logger.info("create szgc datasource url:"+((DruidDataSource) dataSource1).getUrl());
                logger.info("datasource szgc key:"+name);
                targetDataSources.put(name, dataSource1);

                DataSource dataSource2 = DruidDataSourceBuilder.create().build();
//                ((DruidDataSource) dataSource2).setUrl("jdbc:mysql://"+ip+":"+port+"/"+GlobalConstants.USER_PREFIX+nameStr+"?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai");
                ((DruidDataSource) dataSource2).setUrl("jdbc:mysql://"+ip+":"+port+"/"+prefix+"-user"+nameStr+"?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai");
                ((DruidDataSource) dataSource2).setUsername(username);
                ((DruidDataSource) dataSource2).setPassword(password);
                ((DruidDataSource) dataSource2).setDriverClassName(driverClassName);
                targetDataSources.put("user-"+name, dataSource2);
                logger.info("create szgc-user datasource url:"+((DruidDataSource) dataSource2).getUrl());
                logger.info("datasource szgc-user key:"+"user-"+name);
            }
            newSmt.close();
            newConn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}